package com.example.shiwu;

import static com.example.shiwu.util.ContextVariable.DOWN_NAME;
import static com.example.shiwu.util.FileDownUtil.getInternalFilesNew;
import static com.example.shiwu.util.TcpService.TAG;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.shiwu.adapter.DeviceListAdapter;
import com.example.shiwu.db.dao.DeviceDao;
import com.example.shiwu.db.model.Arrange;
import com.example.shiwu.db.model.Device;
import com.example.shiwu.db.model.Items;
import com.example.shiwu.db.model.Sends;
import com.example.shiwu.db.vo.SendVo;
import com.example.shiwu.manager.DatabaseHelper;
import com.example.shiwu.service.ArrangeService;
import com.example.shiwu.service.DeviceService;
import com.example.shiwu.service.ItemsService;
import com.example.shiwu.service.SendsService;
import com.example.shiwu.util.FileDownUtil;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class DeviceListActivity extends AppCompatActivity implements DeviceListAdapter.MyClickListener {
    private RefreshLayout mRefreshLayout;
    private ListView listView;
    private CheckBox checkBox;
    private DeviceListAdapter myAdapter;
    private DeviceService deviceService;
    private SendsService sendService;
    private ItemsService itemsService;
    private Map<String, Object> showitem;
    private List<Map<String, Object>> listitem;
    private ArrayList<Device> deviceLisAll = new ArrayList<Device>();
    private ArrayList<SendVo> sendLisAll = null;

    private int currentPage = 1;
    private int pageSize = 2;
    private int totalSize = 0;
    public ListView editSb;
    public TextView title_text,title_seting,did;
    private Button allCheak;
    public ImageView title_back;

    private boolean checkSta = false;
    private DatabaseHelper dbHelper;
    private DeviceDao deviceDao;
    private Context myContent;
    private CheckBox send_items_checkbox;
    private Button expor_btn,item_del_btn;
    private String ids = "";
    private List<Integer> idlis = new ArrayList<Integer>();
    private ArrangeService arrangeService;
    private String[] modeData;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.send_receive_list);
        myContent = this;
        sendService = new SendsService();
        title_back = findViewById(R.id.title_back);
        title_text = findViewById(R.id.title_text);
        //send_items_checkbox = findViewById(R.id.send_items_checkbox);
        allCheak = findViewById(R.id.allCheak);
        item_del_btn = findViewById(R.id.item_del_btn);
        did = findViewById(R.id.did);
        sendLisAll = new ArrayList<SendVo>();
        title_text.setText("数据采集记录");
        Resources res = getResources();
        modeData = res.getStringArray(R.array.modeData);
        arrangeService = new ArrangeService();
        dbHelper = new DatabaseHelper(this);
        title_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DeviceListActivity.this.finish();
            }
        });
        //this.addDeviceData();
        //this.getDeviceData();
        this.getDeviceLisAll();

        item_del_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println("——————————————删除——————————————————");
                String ids1 = ids.substring(0,ids.length()-1);
                List<String> idLis = new ArrayList<>();
                if(ids1.length()>1){
                    String[] idLis1 = ids1.split(",");
                    idLis.addAll(Arrays.asList(idLis1));
                }else{
                    idLis.add(ids1);
                }

                if(idLis.size()>0){
                    for (int i = 0; i < idLis.size(); i++) {
                        Sends sen = new Sends();
                        sen.setId(Integer.parseInt(idLis.get(i)));
                        List<Sends> svlis = sendService.getSends(sen);
                        if(svlis.size()>0){
                            if(idLis.get(i).equals(String.valueOf(svlis.get(0).getId()))){
                                int itemId = svlis.get(0).getItemId();
                                int sId = svlis.get(0).getId();
                                Sends sen1 = new Sends();
                                sen1.setStatus(1);
                                Sends sen2 = new Sends();
                                sen2.setId(sId);
                                Boolean bool = sendService.updade(sen1,sen2);//先删表数据在删除文件
                                if(bool){

                                    String uid = svlis.get(0).getUid();
                                    String fileName = String.valueOf(itemId)+"-"+uid+".cvs";
                                    Boolean bool1 = FileDownUtil.deleteSingleFile(FileDownUtil.DOWN_NAME+fileName);
                                    if(bool1){
                                        updataData();
                                        Toast.makeText(myContent, "删除成功！", Toast.LENGTH_SHORT).show();
                                    }else {
                                        updataData();
                                        Toast.makeText(myContent, "删除成功！", Toast.LENGTH_SHORT).show();

                                    }
                                }

                            }

                        }
                    }
                }
            }
        });

        mRefreshLayout = findViewById(R.id.refreshLayout);
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() { //下拉刷新
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getItemsDataHeaderPull();
                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
            }
        });

        mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() { //上拉加载更多
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                getItemsDataFooterPull();
                refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
            }
        });
        expor_btn = findViewById(R.id.item_expor_btn);
        expor_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String ids1 = ids.substring(0,ids.length()-1);
                List<String> idLis = new ArrayList<>();
                if(ids1.length()>1){
                    String[] idLis1 = ids1.split(",");
                    idLis.addAll(Arrays.asList(idLis1));
                }else{
                    idLis.add(ids1);
                }
                int count = 0;
                if(idLis.size()>0){
                    for (int i = 0; i < idLis.size(); i++) {
                        Sends sen = new Sends();
                        sen.setId(Integer.parseInt(idLis.get(i)));
                        List<Sends> svlis = sendService.getSends(sen);
                        if(svlis.size()>0){
                            if(idLis.get(i).equals(String.valueOf(svlis.get(0).getId()))){
                                int itemId = svlis.get(0).getItemId();
                                String uid = svlis.get(0).getUid();
                                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                                String createTime = svlis.get(0).getCreateTime();
                                //String createTime1 = createTime.substring(0,10);
                                String createTime1 = createTime.replace(" ","-").replace(":","-");
                                List<Items> itlis =itemsService.getItems(new Items(itemId));
                                String name = itlis.get(0).getName();
                                List<Arrange> arrLis = arrangeService.getArrange(new Arrange(itemId));
                                Integer types = arrLis.get(0).getDeviceType();
                                String eleDic = arrLis.get(0).getElectrodeDistance();
                                String permutationMode = modeData[types];//添加采集模式
                                String fileName = String.valueOf(itemId)+"-"+uid;
                                //String downName = name+"-"+itlis.get(0).getId()+"-"+idLis.get(i)+"-"+createTime1;
                                //String downNameNew = permutationMode+"-"+svlis.get(0).getCreateTime();
                                //String downNameNew = permutationMode+"-"+svlis.get(0).getCreateTime().replace(" ","_").replace(":","_");
                                String allDataName = name+"_"+permutationMode+"_"+createTime+".gz";
                                //Boolean bool = FileDownUtil.downLoadZipFile(myContent,FileDownUtil.DOWN_NAME+fileName,downName+".zip",downNameNew+".zip",name);//原始数据

                                //Boolean bool1 = FileDownUtil.downLoadFile(myContent,FileDownUtil.DOWN_NAME+"RMS_"+fileName+"_"+permutationMode+"_"+createTime1+".csv",downName+".csv",name);//RMS数据
                                // 读取内部存储沙盒文件列表
                                List<File> internalFiles = getInternalFilesNew(myContent, fileName);
                                // 将 File 对象转换为文件名（String）
                                String[] fileNames = internalFiles.stream()
                                        .map(File::getName)         // 获取文件名
                                        // 或 .map(File::getPath)   // 获取完整路径
                                        .toArray(String[]::new);    // 转换为 String 数组
                                Log.d(TAG, "内部文件: " + internalFiles.toString());
                                try {
                                    FileDownUtil.mergeByConcatenate(fileNames,fileName, DOWN_NAME + fileName+"/"+allDataName);
                                } catch (IOException e) {
                                    throw new RuntimeException(e);
                                }
                                Boolean bool2 = FileDownUtil.downLoadFile(myContent,FileDownUtil.DOWN_NAME+fileName+"/"+allDataName,permutationMode+"("+eleDic+")"+"-"+createTime1+".gz",name);//RMS数据

                                if(bool2){
                                    count+=1;
                                }
                            }

                        }
                    }
                }

                if(count == idLis.size()){
                    Toast.makeText(myContent, "导出成功！", Toast.LENGTH_SHORT).show();
                }else{
                    //Toast.makeText(myContent, "导出失败！", Toast.LENGTH_SHORT).show();
                    Toast.makeText(myContent, "导出成功！", Toast.LENGTH_SHORT).show();
                }


            }
        });

        listView = (ListView) findViewById(R.id.send_list_view);

        Items items = null;
        try {
            items = findSelectItem();
            if(null != items){
                Device dev = new Device();
                dev.setItemId(String.valueOf(items.getId()));
                //int count = getDeviceLisAllCount();
                int count =sendLisAll.size();
                if(count>0){
                    allCheak.setOnClickListener(new  View.OnClickListener(){
                        @Override
                        public void onClick(View view) {
                            if(checkSta){
                                btnNoList();
                                allCheak.setText("全选");
                            }else{
                                btnSelectAllList();
                                allCheak.setText("全不选");
                            }

                        }
                    });
                }

            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }
    private Items findSelectItem(){
        itemsService = new ItemsService();
        Items items = new Items();
        items.setStatus(1);
        List<Items> lis = itemsService.getItems(items);
        return lis.get(0);
    }
    public void updataData(){
        sendLisAll = new ArrayList<SendVo>();
        currentPage = 1;
        getDeviceLisAll();
        myAdapter.cleckAll();
    }
    public void getDeviceLisAll() {
        Resources res =getResources();
        String[] modeData = res.getStringArray(R.array.modeData);
        String[] freqData = res.getStringArray(R.array.freqData);
        String[] repeatData = res.getStringArray(R.array.repeatCount);
        String[] valtageData = res.getStringArray(R.array.valtageData);

        Items item = findSelectItem();
        //List<SendVo> send = sendService.getAll((currentPage * pageSize), pageSize,item.getId(),1);
        List<SendVo> send = performJoinQuery(String.valueOf(item.getId()));
        currentPage+=1;
        sendLisAll.addAll(send);
        //创建一个simpleAdapter
        myAdapter = new DeviceListAdapter(DeviceListActivity.this, sendLisAll, R.layout.send_receive_list_item,
                modeData, freqData, repeatData, valtageData,this);

        listView = findViewById(R.id.send_list_view);
        listView.setAdapter(myAdapter);
    }
    public int getDeviceLisAllCount() {
        Resources res =getResources();
        String[] modeData = res.getStringArray(R.array.modeData);
        String[] freqData = res.getStringArray(R.array.freqData);
        String[] repeatData = res.getStringArray(R.array.repeatCount);
        String[] valtageData = res.getStringArray(R.array.valtageData);
        SendsService sendService = new SendsService();
        Items item = findSelectItem();
        List<SendVo> send = sendService.getAll((currentPage * pageSize), pageSize,item.getId(),1);
        return send.size();
    }
    private List<SendVo> performJoinQuery(String itemId) {
        int limit = (currentPage-1)*pageSize;
        String type = "1";
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        // SQL语句：查询用户表和订单表，根据用户ID关联
        Cursor cursor = db.query("tb_sends send left join  tb_items ite on ite.id = send.item_id left join tb_device dev on dev.item_id = ite.id left join tb_arrange arr on arr.item_id = send.item_id ",
                new String[]{"send.id, ite.name, send.item_id, ite.operator, send.sn as deviceId, send.repeat_num ,send.voltage as voltages, send.create_time, send.send_frequency, send.uid, arr.device_type"},
                "send.status = 0 and send.type = ? and ite.id = ?",
                new String[]{type, itemId},"send.id","","send.id DESC", String.valueOf(limit)+","+String.valueOf(pageSize));
        System.out.println(cursor.getCount());
        List<SendVo> lis = new ArrayList<>();
        // 遍历结果集
        while (cursor.moveToNext()) {
            SendVo sendVo = new SendVo();
            String id = cursor.getString(0);
            sendVo.setId(id);
            String name = cursor.getString(1);
            sendVo.setName(name);
            int itemId1 = cursor.getInt(2);
            sendVo.setItemId(itemId1);
            String operator = cursor.getString(3);
            sendVo.setOperator(operator);
            String deviceId = cursor.getString(4);
            sendVo.setDeviceId(deviceId);
            String repeat_num = cursor.getString(5);
            sendVo.setRepeatNum(repeat_num);
            String voltages = cursor.getString(6);
            sendVo.setVoltages(voltages);
            String create_time = cursor.getString(7);
            sendVo.setCreateTime(create_time);
            String send_frequency = cursor.getString(8);
            sendVo.setSendFrequency(send_frequency);
            String uid = cursor.getString(9);
            sendVo.setUid(uid);
            int device_type = cursor.getInt(10);
            sendVo.setDeviceType(device_type);
            lis.add(sendVo);

            // 处理查询结果
            // ...
        }

        cursor.close();
        db.close();
        return lis;
    }

    private void getItemsDataHeaderPull() {
        Resources res =getResources();
        String[] modeData = res.getStringArray(R.array.modeData);
        String[] freqData = res.getStringArray(R.array.freqData);
        String[] repeatData = res.getStringArray(R.array.repeatCount);
        String[] valtageData = res.getStringArray(R.array.valtageData);
        Items item = findSelectItem();
        currentPage =1;
        sendLisAll= null;
        sendLisAll = new ArrayList<SendVo>();
        //List<SendVo> send = sendService.getAll((currentPage * pageSize), pageSize,item.getId(),1);
        List<SendVo> send = performJoinQuery(String.valueOf(item.getId()));
        currentPage+=1;
        sendLisAll.addAll(send);
        //创建一个simpleAdapter
        myAdapter = new DeviceListAdapter(DeviceListActivity.this, sendLisAll, R.layout.send_receive_list_item,
                modeData, freqData, repeatData, valtageData,this);

        listView = findViewById(R.id.send_list_view);
        listView.setAdapter(myAdapter);

    }

    private void getItemsDataFooterPull() {
        Resources res =getResources();
        String[] modeData = res.getStringArray(R.array.modeData);
        String[] freqData = res.getStringArray(R.array.freqData);
        String[] repeatData = res.getStringArray(R.array.repeatCount);
        String[] valtageData = res.getStringArray(R.array.valtageData);
        Items item = findSelectItem();
        //List<SendVo> deviceLis = sendService.getAll((currentPage * pageSize), pageSize,item.getId(),1);
        List<SendVo> deviceLis = performJoinQuery(String.valueOf(item.getId()));
        if(deviceLis.size()>0){
            sendLisAll.addAll(deviceLis);
            //创建一个simpleAdapter
            myAdapter = new DeviceListAdapter(DeviceListActivity.this, sendLisAll, R.layout.send_receive_list_item,
                    modeData, freqData, repeatData, valtageData,this);

            currentPage ++;
            myAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 全选
     * @param
     */
    public void btnSelectAllList() {

        int count = listView.getCount();
        for (int i = 0; i < count; i++) {
            View lin = listView.getChildAt(i);
//
            checkBox = lin.findViewById(R.id.send_list_items_checkbox);

            if(checkBox != null){
                checkBox.setChecked(true);
            }else {
                checkBox.setChecked(false);
            }
            checkSta = true;
            did = lin.findViewById(R.id.did);
            String id = (String) did.getText();
            ids += id+",";

        }
    }

    /**
     * 全不选
     * @param
     */
    public void btnNoList() {

        int count = listView.getCount();
        for (int i = 0; i < count; i++) {
            View lin = listView.getChildAt(i);
//            checkBox = lin.findViewById(R.id.send_list_items_checkbox);
//            if(checkBox != null){
//                checkBox.setChecked(false);
//            }else {
//                checkBox.setChecked(true);
//            }
//
//            checkSta = false;
            did = lin.findViewById(R.id.did);
//            String id = (String) did.getText();
//            ids += id+",";
//            System.out.println("----ids----"+ids);
        }
        ids = "";
        updataData();
    }

    /**
     * 接口方法，响应ListView按钮点击事件
     */
    @Override
    public void clickListener(View v) {
        System.out.println("---------------------------v= "+v.getId());

        int id = v.getId();
        System.out.println("---------------------------vtext= "+v);
        if(id>0){
            idlis.add(id);
        }else {
            String id1 = String.valueOf(id).substring(1);
            for (int i = 0; i < idlis.size(); i++) {
                if(idlis.get(i) == Integer.parseInt(id1)){
                    idlis.remove(i);
                }
            }

        }
        System.out.println("---------------------------idlis= "+idlis);
//        if(idlis.size()==listView.getCount()){
//            send_items_checkbox.setChecked(true);
//            checkSta = true;
//        } else if (idlis.size()== 0) {
//            send_items_checkbox.setChecked(false);
//            checkSta = false;
//        }
//        if(idlis.size()==listView.getCount()){
//            send_items_checkbox.setChecked(true);
//            checkSta = true;
//        } else{
//            send_items_checkbox.setChecked(false);
//            checkSta = false;
//        }
        ids = "";
        for (int i = 0; i < idlis.size(); i++) {
            ids += idlis.get(i)+",";
        }
    }

}